//获取url中的参数
export function getUrlParam(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg); //匹配目标参数
  if (r != null)
    return decodeURI(r[2]);
  else
    return null; //返回参数值
}

// 获取用户使用时间
export function getAge(birthday, currentDate) {
  try {
    var reg = new RegExp(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
    var birthdayArr = birthday.match(reg);
    var currentDateArr = currentDate.match(reg);
    var beginArr = [];
    var endArr = [];

    var days = 0;
    var month = 0;
    var year = 0;

    days = currentDateArr[4] - birthdayArr[4];
    if (days < 0) {
      month = -1;
      days = 30 + days;
    }

    month = month + (currentDateArr[3] - birthdayArr[3]);
    if (month < 0) {
      year = -1;
      month = 12 + month;
    }

    year = year + (currentDateArr[1] - birthdayArr[1]);

    var yearString = year > 0 ? year + "岁" : "";
    var mnthString = month > 0 ? month + "个月" : "";
    var dayString = days > 0 ? days + "天" : "";

    /*
     * 1 如果岁 大于等于1 那么年龄取 几岁 2 如果 岁等于0 但是月大于1 那么如果天等于0
     天小于3天 取小时
     * 例如出生2天 就取 48小时
     */
    var result = "";
    if (year >= 100) {
      result = "未设置"
    } else if (year >= 1) {
      result = yearString + mnthString;
    } else {
      if (month >= 1) {
        result = days > 0 ? mnthString + dayString : mnthString;
      } else {
        var begDate = new Date(beginArr[1], beginArr[3] - 1,
          beginArr[4], beginArr[6], beginArr[8], beginArr[10]);
        var endDate = new Date(endArr[1], endArr[3] - 1, endArr[4],
          endArr[6], endArr[8], endArr[10]);

        var between = (endDate.getTime() - begDate.getTime()) / 1000;
        days = Math.floor(between / (24 * 3600));
        var hours = Math.floor(between / 3600 - (days * 24));
        dayString = days > 0 ? days + "天" : "";
        result = days >= 3 ? dayString : days * 24 + hours + "小时";
      }
    }

    return result;
  } catch (error) {
    return "";
  }
}

//获取当前时间，格式YYYY-MM-DD
export function getCurrentDateStr() {
  var date = new Date();
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1; //JavaScript中Date类的getMonth方法的返回值比实际月份少一
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

export function isWx() {
  return navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger"
}